#include"file2file.h"

#define CACHE 256
#define MAX_CACHE 1024

char* getFileName(char* source)
{
    int i = 0;
    int index = 0;
    char* fileName = (char *)malloc(MAX_CACHE);
    while(source[i] != '\0')
    {
        // 找到最后一个'/'的位置
        if (source[i] == '/')
        {
            index = i;
        }
        i++;
    }
    int j = index + 1;           // 过滤前面的'/'
    int from = 0;
    while(source[j] != '\0')
    {
        fileName[from] = source[j];
        j++;
        from++;
    }
    fileName[from] = '\0';
    return fileName;
}

void file2file(int fin, int fout)
{
	char* bufs = (char *)malloc(CACHE);
	char* content = (char *)malloc(MAX_CACHE);
	ssize_t ret;
	int total = 0;
	while((ret = read(fin, bufs, CACHE)) != 0)   // 文件拷贝
	{
		if (ret == -1) {
        	if (errno == EINTR) {
            	continue;     
        	}
        	perror("read");
        	break;
    	}
    	total += ret;
    	strcat(content, bufs);
	}
	write(fout, content, total);
}

void mycp(char **argv)
{
    int f1 = open(argv[0], O_RDONLY);
	if (f1 == -1)                       // 源文件不存在
	{
		perror(argv[0]);
        return;
	}
    char* fileName = getFileName(argv[0]);
    char* tmp = (char *)malloc(200);
    strcpy(tmp, argv[1]);
    strcat(tmp, fileName);
    int f2 = open(tmp, O_WRONLY|O_CREAT, S_IRUSR | S_IWUSR);
    if (f2 == -1)
    {
        perror(argv[1]);
        return;
    }
    file2file(f1, f2);
    printf("%s%s%s%s\n", "The source file ", fileName, " had been cp to target: ", argv[1]);

    // 关闭文件
    close(f1);
    close(f2);
}
